﻿using Microsoft.Extensions.Logging;
using System;
using System.Net.Http;

namespace Longbow.Web
{
    /// <summary>
    ///
    /// </summary>
    internal class DefaultIPLocator : IIPLocator
    {
        /// <summary>
        ///
        /// </summary>
        /// <param name="option"></param>
        /// <returns></returns>
        public virtual string Locate(IPLocatorOption option) => null;

        /// <summary>
        ///
        /// </summary>
        /// <param name="option"></param>
        /// <returns></returns>
        protected string Locate<T>(IPLocatorOption option)
        {
            var ret = default(T);
            try
            {
                if (string.IsNullOrEmpty(option.Url)) return string.Empty;

                var task = option.HttpClient.GetAsJsonAsync<T>(option.Url);
                task.Wait(option.RequestTimeout);
                if (task.IsCompleted && !task.IsFaulted) ret = task.Result;
            }
            catch (Exception ex)
            {
                option.Logger.LogError(ex, option.Url);
            }
            return ret?.ToString();
        }
    }
}
